package com.cee.quartz.component;

import org.quartz.CronExpression;
import org.quartz.SchedulerException;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;


public class CronUtils {

    private static final String DATE_FORMATTER = "ss mm HH dd MM ? yyyy";
    private static final String CRON_START_DAY = "1";
    private static final String CRON_END_DAY = "31";
    private static final String CRON_START_MONTH = "1";
    private static final String CRON_END_MONTH = "12";
    private static final String CRON_SPACE = " ";
    private static final String CRON_MARK = "?";
    private static final String CRON_AND = "-";

    public static String formatCronExpression(Date date) {
        if (date == null) {
            throw new IllegalArgumentException("date could not be null!");
        }
        SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMATTER);
        String cronExpression = null;

        if (date != null) {
            cronExpression = sdf.format(date);
        }

        return cronExpression;
    }

    public static boolean isCornExpression(String cornExpression) {
        try {
            CronExpression exp = new CronExpression(cornExpression);
            Date d = new Date();
            d = exp.getNextValidTimeAfter(d);
            return d != null ? true : false;
        } catch (ParseException e) {
            return false;
        }

    }

    public static Date getFirstCornExpression(String cornExpression) throws ParseException {
        Date d = new Date();
        CronExpression exp = new CronExpression(cornExpression);
        d = exp.getTimeAfter(d);
        return d;
    }

}
